package com.huawei.codearts.config.version;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.servlet.mvc.condition.RequestCondition;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class ApiVersionCondition implements RequestCondition<ApiVersionCondition> {
    private final static Pattern VERSION_PREFIX_PATTERN = Pattern.compile(".*v(\\d+).*");
    private final int apiVersion;

    ApiVersionCondition(int apiVersion) {
        this.apiVersion = apiVersion;
    }

    public int getApiVersion() {
        return apiVersion;
    }

    @Override
    public ApiVersionCondition combine(ApiVersionCondition apiVersionCondition) {
        return new ApiVersionCondition(apiVersionCondition.getApiVersion());
    }

    @Override
    public ApiVersionCondition getMatchingCondition(HttpServletRequest httpServletRequest) {
//        System.out.println("ApiVersionCondition...getMatchingCondition...httpServletRequest.getRequestURI()={}"+httpServletRequest.getRequestURI());
//        if (this.apiVersion == 0) {
//            return this;
//        }
        Matcher m = VERSION_PREFIX_PATTERN.matcher(httpServletRequest.getRequestURI());
        if (m.find()) {
            int version = Integer.parseInt(m.group(1));
            /**
             * 自动向上查找小版本api
             */
            if (version >= this.apiVersion) {
//                System.out.println("ApiVersionCondition...getMatchingCondition...version="+version+", apiVersion={}"+this.apiVersion);
                return this;
            }
        }

        return null;
    }

    @Override
    public int compareTo(ApiVersionCondition other, HttpServletRequest request) {
//        System.out.println("ApiVersionCondition...compareTo...version="+other.getApiVersion()+", apiVersion={}"+this.apiVersion);
        // 比较版本 从大到小 个人理解: 返回=0: 表示当前ver版本的api路由, 返回<0: 表示小于当前ver版本的api路由
        return other.getApiVersion() - this.apiVersion;
    }

}